(function(){
    var items = $('.mainMenu > menuitem');
    for(var i = 0, l = items.length; i < l; i++){
        var transition = 'margin-left 0.4s ease-in-out ' + (0.4 / (l - 1) * i) + 's, color 0.1s linear, background-color 0.2s linear';
        items.eq(i).css('transition', transition);
    }
    function hideMenu(event){
        if(event && event.target && $('.mainMenu')[0].contains(event.target)) return;
        $('.mainMenu').removeClass('mainMenuShow').find('.subMenuShow').removeClass('subMenuShow');
        $('.mainContainer').removeClass('mainContainerHide');
        document.removeEventListener('mousedown', hideMenu, true);
        document.removeEventListener('touchstart', hideMenu, true);
        setTimeout(function(){$('.menuButton').bind('click', showMenu);}, 400); //wait until the animation finished
        event.stopPropagation();
        event.cancelBubble = true; //for IE10 metro
    }
    function showMenu(){
        $('.mainMenu').addClass('mainMenuShow');
        $('.mainContainer').addClass('mainContainerHide');
        document.addEventListener('mousedown', hideMenu, true);
        document.addEventListener('touchstart', hideMenu, true);
        $('.menuButton').unbind('click', showMenu);
    }
    $('.menuButton').bind('click', showMenu);

    $('.mainMenu').on('click', '> menuItem', function(){
        $('.mainMenu .subMenuShow').removeClass('subMenuShow');
        $(this).addClass('subMenuShow');
    })
})();